package com.mybatisx.mybatisplus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mybatisx.mybatisplus.entity.Users;
import com.mybatisx.mybatisplus.mapper.UsersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author wuyue
 * @date 2021/6/23 9:59
 */
@Service("userDetailsService")
public class    MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UsersMapper usersMapper;
    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        // 定义查询条件，根据用户名 从数据库查询 对应的 用户、密码、角色
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", name);
        Users user = usersMapper.selectOne(queryWrapper);
        // 用户不存在时，直接抛异常
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        // 用户存在时，把 用户、密码、角色 加入到当前认证系统中
        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList(user.getRole());
        // 将数据库中的密码进行 加密
        return new User(user.getName(), new BCryptPasswordEncoder().encode(user.getPassword()), auths);
//        return new User(user.getName(), user.getPassword(), auths); // 若数据库密码已经加密过，直接使用即可

    }
}
